import os
import sys
import time


sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from model import OpenAIModel
from translator import PDFTranslator
from fastapi import FastAPI, File, Form, UploadFile
from fastapi.staticfiles import StaticFiles


model_name = 'gpt-3.5-turbo'
api_key = 'your-openai-api-key'
base_url = 'change openai api base url if necessary'
model = OpenAIModel(model=model_name, api_key=api_key, base_url=base_url)
translator = PDFTranslator(model)

domain = "the servers' domain"

app = FastAPI()
app.mount("/static", StaticFiles(directory="upload_files"), name="static")
@app.post("/translate/")
async def login(fileb: UploadFile = File(), file_format: str = Form(), target_language: str = Form()):
    # save uploaded file
    timestamp = time.time()
    if fileb.content_type != 'application/pdf':
        return {
            'msg': 'please upload pdf file'
        }
    filename_list = fileb.filename.split('.')
    tmp_filename = ''.join(filename_list[:-1]) + '_' + str(int(round(timestamp, 0)))
    with open(f"upload_files/{tmp_filename}.pdf", 'wb') as f:
        for i in iter(lambda: fileb.file.read(1024 * 1024), b''):
            f.write(i)
    translator.translate_pdf(f"upload_files/{tmp_filename}.pdf", file_format, target_language=target_language)
    return {
        "translated_file": f"{domain}/static/{tmp_filename}_translated.md"
    }
